package com.micro.ai.template.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.dto.request.TemplateCreateRequest;
import com.micro.ai.template.dto.request.TemplateUpdateRequest;
import com.micro.ai.template.dto.response.TemplateDTO;
import com.micro.ai.template.service.TemplateService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 模板管理控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/templates")
@Tag(name = "模板管理", description = "AI Agent模板的CRUD操作、版本管理、启用禁用等")
public class TemplateController {

    @Autowired
    private TemplateService templateService;

    @PostMapping
    @PreAuthorize("hasAuthority('template:create')")
    @Operation(summary = "创建模板", description = "创建新的AI Agent模板")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", 
            content = @Content(schema = @Schema(implementation = TemplateDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<TemplateDTO> createTemplate(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Valid @RequestBody TemplateCreateRequest request) {
        log.info("创建模板: userId={}, tenantId={}, templateName={}", userId, tenantId, request.getTemplateName());
        
        TemplateDTO template = templateService.createTemplate(userId, tenantId, request);
        
        return ApiResponse.success("创建成功", template);
    }

    @PutMapping("/{templateId}")
    @PreAuthorize("hasAuthority('template:update')")
    @Operation(summary = "更新模板", description = "更新模板基本信息")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功",
            content = @Content(schema = @Schema(implementation = TemplateDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在")
    })
    public ApiResponse<TemplateDTO> updateTemplate(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "模板ID") @PathVariable String templateId,
            @Valid @RequestBody TemplateUpdateRequest request) {
        log.info("更新模板: userId={}, templateId={}", userId, templateId);
        
        TemplateDTO template = templateService.updateTemplate(userId, tenantId, templateId, request);
        
        return ApiResponse.success("更新成功", template);
    }

    @DeleteMapping("/{templateId}")
    @PreAuthorize("hasAuthority('template:delete')")
    @Operation(summary = "删除模板", description = "删除模板（软删除）")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权删除")
    })
    public ApiResponse<Void> deleteTemplate(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        log.info("删除模板: userId={}, templateId={}", userId, templateId);
        
        templateService.deleteTemplate(userId, tenantId, templateId);
        
        return ApiResponse.<Void>success(null);
    }

    @GetMapping("/{templateId}")
    @Operation(summary = "获取模板详情", description = "获取模板的详细信息")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
    	@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = TemplateDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在")
    })
    public com.micro.ai.commons.domain.ApiResponse<TemplateDTO> getTemplate(
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        log.info("获取模板详情: templateId={}", templateId);
        
        TemplateDTO template = templateService.getTemplateById(templateId);
        
        return ApiResponse.success(template);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询模板", description = "分页查询模板列表，支持多条件筛选")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @io.swagger.v3.oas.annotations.media.Content(schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = Page.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误")
    })
    public ApiResponse<Page<TemplateDTO>> listTemplates(
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "分类ID") @RequestParam(required = false) String categoryId,
            @Parameter(description = "模板名称") @RequestParam(required = false) String templateName,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        log.info("分页查询模板: tenantId={}, pageNum={}, pageSize={}", tenantId, pageNum, pageSize);
        
        Page<TemplateDTO> page = templateService.listTemplates(tenantId, pageNum, pageSize, 
                categoryId, templateName, status);
        
        return ApiResponse.success(page);
    }

    @GetMapping("/my")
    @Operation(summary = "我的模板", description = "查询当前用户创建的所有模板")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @io.swagger.v3.oas.annotations.media.Content(schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = Page.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权")
    })
    public ApiResponse<Page<TemplateDTO>> getMyTemplates(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("查询我的模板: userId={}, tenantId={}", userId, tenantId);
        
        Page<TemplateDTO> page = templateService.getMyTemplates(userId, tenantId, pageNum, pageSize);
        
        return ApiResponse.success(page);
    }

    @PutMapping("/{templateId}/status")
    @PreAuthorize("hasAuthority('template:update')")
    @Operation(summary = "更新模板状态", description = "启用或禁用模板")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "状态更新成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Void> updateTemplateStatus(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "模板ID") @PathVariable String templateId,
            @Parameter(description = "是否启用") @RequestParam Boolean enabled) {
        log.info("更新模板状态: userId={}, templateId={}, enabled={}", userId, templateId, enabled);
        
        templateService.updateTemplateStatus(userId, tenantId, templateId, enabled);
        
        return ApiResponse.<Void>success(null);
    }

    @PostMapping("/{templateId}/clone")
    @PreAuthorize("hasAuthority('template:create')")
    @Operation(summary = "克隆模板", description = "复制现有模板创建新模板")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "克隆成功",
            content = @Content(schema = @Schema(implementation = TemplateDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "源模板不存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public com.micro.ai.commons.domain.ApiResponse<TemplateDTO> cloneTemplate(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        log.info("克隆模板: userId={}, templateId={}", userId, templateId);
        
        TemplateDTO template = templateService.cloneTemplate(userId, tenantId, templateId);
        
        return ApiResponse.success("克隆成功", template);
    }
}
